package com.hoow.shakoow.shake

import android.annotation.SuppressLint
import android.os.*
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.hoow.shakoow.ai.data.ReqChatInfo
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.databinding.ActivityUserChatInfoBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.shake.adapter.ChatInfoAdapter
import com.bumptech.glide.Glide
import com.hoow.shakoow.ai.data.ReqAiBase
import com.hoow.shakoow.ai.data.ReqReadGreetMsg
import com.hoow.shakoow.utils.analytics.util.AnalyticsUtil


/** 摇到的人页 */
@SuppressLint("CustomSplashScreen")
class UserChatInfoActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityUserChatInfoBinding

    // 适配器
    private lateinit var mChatInfoAdapter: ChatInfoAdapter

    // 消息滑动线程句柄
    private val mScrollToBottomHandler: Handler = Handler(Looper.getMainLooper())

    // 消息滑动线程句柄
    private val mRefreshHandler: Handler = Handler(Looper.getMainLooper())

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.chat_info.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivityUserChatInfoBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n", "SourceLockedOrientationActivity", "NotifyDataSetChanged")
    override fun onContentViewBinded() {
        try {
            // 初始化适配器
            mChatInfoAdapter = ChatInfoAdapter(mNetworkViewModel.mChatInfoMsgList)
            mActivityBinding.rcShakeHistoryList.layoutManager = LinearLayoutManager(this)
            mActivityBinding.rcShakeHistoryList.adapter = mChatInfoAdapter

            // 初始化下拉刷新
            mActivityBinding.srlLayout.buildRefreshConfigs(this) {
                // 获取聊天列表
                getChatList(false)
            }

            // 监听接口返回
            mNetworkViewModel.onGetChatInfoLiveData.observe(this) {
                mActivityBinding.srlLayout.isRefreshing = false

                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        // 更新图片
                        result.headImg?.let { url ->
                            if (url.isValidLink()) {
                                Glide.with(mActivityBinding.imageUserAvatarValue)
                                    .load(url)
                                    .into(mActivityBinding.imageUserAvatarValue)
                            }
                        }

                        // 更新性名
                        mActivityBinding.textUserNickNameValue.text = result.name

                        // 更新消息列表
                        result.chatMsgRespList?.let { list ->
                            // 清空列表
                            mNetworkViewModel.mChatInfoMsgList.clear()
                            mNetworkViewModel.mChatInfoMsgList.addAll(list)

                            // 更新列表
                            mChatInfoAdapter.notifyDataSetChanged()
                        }

                        // 确认已读消息
                        val sbId = intent.getStringExtra("sbId") ?: ""
                        val reqReadGreetMsg = ReqReadGreetMsg(sbId = sbId)
                        reqReadGreetMsg.showLoading = false
                        mNetworkViewModel.readGreetMsg(reqReadGreetMsg)

                        // 1秒后滑动
                        mScrollToBottomHandler.removeCallbacksAndMessages(null)
                        mScrollToBottomHandler.postDelayed({
                            mActivityBinding.rcShakeHistoryList.scrollToPosition(mNetworkViewModel.mChatInfoMsgList.size - 1)
                        }, 500)
                    }
                }

                // 延时执行
                delayQueryAction()
            }

            // 阅读监听
            mNetworkViewModel.onReadGreetMsgLiveData.observe(this) {

            }

            // 点击回复
            mActivityBinding.textToGreet.setOnClickListener {
                val userId = intent.getStringExtra("userId") ?: ""
                val shakeId = intent.getStringExtra("shakeId") ?: ""
                val sbId = intent.getStringExtra("sbId") ?: ""
                val params = HashMap<String, String>()
                params["userId"] = userId
                params["shakeId"] = shakeId
                params["sbId"] = sbId
                startToReplyPage(params)
            }

            // 点击头像
            mActivityBinding.imageUserAvatarValue.setOnClickListener {
                // 组装数据
                val userId = intent.getStringExtra("userId") ?: ""
                val shakeId = intent.getStringExtra("shakeId") ?: ""
                val sbId = intent.getStringExtra("sbId") ?: ""
                val params = HashMap<String, String>()
                params["userId"] = userId
                params["shakeId"] = shakeId
                params["sbId"] = sbId

                // 跳转详情页
                startToUserDetailPage(params)

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "CHAT_AVATAR_CLICK",
                    remark = ""
                )
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()

        // 获取聊天列表
        getChatList(true)
    }

    override fun onPause() {
        mRefreshHandler.removeCallbacksAndMessages(null)
        mScrollToBottomHandler.removeCallbacksAndMessages(null)
        super.onPause()
    }

    override fun onDestroy() {
        mScrollToBottomHandler.removeCallbacksAndMessages(null)
        mRefreshHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    // 延时执行
    private fun delayQueryAction() {
        // 10秒刷新
        mRefreshHandler.removeCallbacksAndMessages(null)
        mRefreshHandler.postDelayed({
            println("=======获取聊天列表")
            // 获取聊天列表
            getChatList(false)

        }, 5000)
    }

    // 获取聊天列表
    private fun getChatList(showLoading: Boolean = true) {
        // 获取聊天列表
        val sbId = intent.getStringExtra("sbId") ?: ""
        val reqChatInfo = ReqChatInfo(sbId = sbId)
        reqChatInfo.showLoading = showLoading
        mNetworkViewModel.getChatInfo(reqChatInfo)
    }
}